<template>
	<view class="container">
		<!-- 空白页 -->
		<view v-if="!hasLogin || cartList.length==0" class="empty">
			<image src="/static/emptyCart.jpg" mode="aspectFit"></image>
			<view v-if="hasLogin" class="empty-tips">
				空空如也
				<navigator class="navigator" v-if="hasLogin" url="../index/index" open-type="switchTab">随便逛逛></navigator>
			</view>
			<view v-else class="empty-tips">
				空空如也
				<view class="navigator" @click="navToLogin">去登录</view>
			</view>
		</view>
		<view v-else>
			<!-- 列表 -->
			<view class="cart-list">
				<block v-for="(item, index) in cartList" :key="index">
					<view class="cart-item" :class="{'b-b': index!==cartList.length-1}">
						<view class="image-wrapper">
							<image :src="item.goods.goodsImg" mode="aspectFill" lazy-load></image>
							<view class="yticon icon-xuanzhong2 checkbox" :class="{checked: item.isCheck==1}" @click="check('item' ,index)"></view>
						</view>
						<view class="item-right">
							<text class="clamp title">{{item.goods.goodsName}}</text>
							<text class="attr">当前库存{{item.goods.stock}}</text>
							<text class="price">¥{{item.goods.price}}</text>
							<uni-number-box class="step" :min="1" :max="item.goods.stock" :value="item.cartNum" :isMax="item.cartNum>=item.goods.stock?true:false"
							 :isMin="item.cartNum===1" :index="index" @eventChange="numberChange"></uni-number-box>
						</view>
						<text class="del-btn yticon icon-fork" @click="deleteCartItem(index)"></text>
					</view>
				</block>
			</view>
			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="checkbox">
					<image :src="allChecked?'/static/selected.png':'/static/select.png'" mode="aspectFit" @click="check('all')"></image>
					<view class="clear-btn" :class="{show: allChecked}" @click="clearCart">
						清空
					</view>
				</view>
				<view class="total-box">
					<text class="price">¥{{total}}</text>
					<!-- <text class="coupon">
						已优惠
						<text>74.35</text>
						元
					</text> -->
				</view>
				<button type="primary" class="no-border confirm-btn" @click="createOrder">去结算</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import uniNumberBox from '@/components/uni-number-box.vue'
	export default {
		components: {
			uniNumberBox
		},
		data() {
			return {
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				empty: false, //空白页现实  true|false
				cartList: [],
				allowModifyItem: true,
				hasLogin: false,
			};
		},

		onShow() {
			let route = getCurrentPages()
			console.log(route[0].route)
			console.log('show')
			let userInfo = uni.getStorageSync('userInfo')
			this.hasLogin = userInfo ? true : false
			if (userInfo) {
				this.loadData();
			}

		},

		methods: {
			//请求数据
			async loadData() {
				// let list = await this.$api.json('cartList');
				// let cartList = list.map(item => {
				// 	item.checked = true;
				// 	return item;
				// });
				// this.cartList = cartList;
				// this.calcTotal(); //计算总价
				let that = this
				that.$Request.request('/api/cart/index', 'GET', {}).then(res => {
					if (res.status == 1) {
						that.cartList = res.data.list
						that.calcTotal();
					}
					console.log(res)
				}).catch(err => {
					console.log(err)
				})
			},
			//监听image加载完成
			onImageLoad(key, index) {
				this.$set(this[key][index], 'loaded', 'loaded');
			},
			//监听image加载失败
			onImageError(key, index) {
				this[key][index].image = '/static/errorImage.jpg';
			},
			navToLogin() {
				console.log('login')
				// #ifdef APP-PLUS
				uni.navigateTo({
					url: '/pages/public/login'
				})
				// #endif

				// #ifdef MP-WEIXIN
				uni.navigateTo({
					url: '../public/login'
				})
				// #endif

			},
			//选中状态处理
			check(type, index) {
				if (type === 'item') {
					if (!this.allowModifyItem) {
						return
					}
					let that = this
					let cat = that.cartList[index]
					that.$Request.request('/api/cart/chooseCart', 'POST', {
						cartIds: cat.cartId,
						isCheck: cat.isCheck == 1 ? 0 : 1
					}).then(res => {
						if (res.status == 1) {
							that.cartList[index].isCheck = that.cartList[index].isCheck == 1 ? 0 : 1
							that.calcTotal(type);
						}
					}).catch(err => {
						console.log(err)
					})


				} else {
					const checked = !this.allChecked
					const list = this.cartList;
					let ids = ''
					list.forEach(item => {
						ids = ids + item.cartId + ','
					})
					let that = this
					that.$Request.request('/api/cart/chooseCart', 'POST', {
						cartIds: ids,
						isCheck: checked ? 1 : 0
					}).then(res => {
						if (res.status == 1) {
							list.forEach(item => {
								item.isCheck = checked ? 1 : 0;
							})
							that.allChecked = checked;
							that.calcTotal(type);
						}
					}).catch(err => {
						console.log(err)
					})
					// 等待全选接口

				}

			},
			//数量
			numberChange(data) {
				let cart = this.cartList[data.index]
				let that = this
				that.$Request.request('/api/cart/changeCartNum', 'POST', {
					cartId: cart.cartId,
					cartNum: data.number
				}).then(res => {
					if (res.status == 1) {

						that.cartList[data.index].cartNum = data.number;
						that.calcTotal();
					}
				}).catch(err => {
					console.log(err)
				})

			},
			//删除
			deleteCartItem(index) {
				let list = this.cartList;
				let row = list[index];
				let id = row.cartId;
				this.delCart(id, (res) => {
					this.cartList.splice(index, 1);
					this.calcTotal();
				})
			},
			delCart(id, success, fail) {
				let that = this
				that.$Request.request('/api/cart/del', 'POST', {
					cartIds: id
				}).then(res => {
					if (res.status == 1) {

						success(res)
					}
				}).catch(err => {
					console.log(err)
					if (fail) {
						fail(err)
					}
				})
			},
			//清空
			clearCart() {
				uni.showModal({
					content: '清空购物车？',
					success: (e) => {
						if (e.confirm) {
							// 等待情况接口
							let ids = ''
							this.cartList.forEach(item => {
								ids = ids + item.cartId + ','
							})
							this.delCart(ids, () => {
								this.cartList = [];
							})

						}
					}
				})
			},
			//计算总价
			calcTotal() {
				let list = this.cartList;
				if (list.length === 0) {
					this.empty = true;
					return;
				}
				let total = 0;
				let checked = true;
				list.forEach(item => {
					if (item.isCheck === 1) {
						total += parseFloat(item.goods.price) * item.cartNum;
					} else {
						checked = false;
					}
				})
				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},
			//创建订单
			createOrder() {
				let list = this.cartList;
				let goodsData = [];
				list.forEach(item => {
					if (item.checked) {
						goodsData.push({
							attr_val: item.attr_val,
							number: item.number
						})
					}
				})

				uni.navigateTo({
					url: `/pages/order/createOrder?data=${JSON.stringify({
						goodsData: goodsData
					})}`
				})
				this.$api.msg('跳转下一页 sendData');
			}
		}
	}
</script>

<style lang='scss'>
	@import './cart.scss'
</style>
